Scroll Progress Bar

In C, an array is a collection of elements of the same data type, stored in contiguous memory locations. It provides a way to store multiple values of the same data type under a single variable name. The elements in an array can be accessed using their index, which starts from 0 and goes up to the array size minus one.

Usage and Syntax:

To declare an array in C, you specify the data type of the elements followedby the array name and the size of the array in square brackets.

data_type array_name[size];

Sample Code with Explanation and Output:

#include <stdio.h>

int main() {
    // Declaration and initialization of an integer array
    int numbers[5] = {10, 20, 30, 40, 50};

    // Accessing array elements using index
    printf("Array Elements: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    // Modifying array elements
    numbers[2] = 35; // Change the value at index 2 to 35

    // Accessing and printing the modified array
    printf("Modified Array: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    // Calculate the sum of all elements in the array
    int sum = 0;
    for (int i = 0; i < 5; i++) {
        sum += numbers[i];
    }
    printf("Sum of array elements: %d\n", sum);

    return 0;
}
Output:

Array Elements: 10 20 30 40 50
Modified Array: 10 20 35 40 50
Sum of array elements: 155
Explanation:
  • In the sample code, declare an integer array numbers of size 5 and initialize it with values {10, 20, 30, 40, 50}.
  • Use a for loop to access and print the array elements using their indices.
  • After that, modify the value at index 2 to 35 (changing 30 to 35).
  • Next, access and print the modified array.
  • Finally, calculate the sum of all elements in the array using a loop and print the sum.

What is a collection of elements of the same data type in C?


Array

What is the position of the first element in an array in C?


Zero

What do you use to access elements in an array in C?


Index

What is the maximum number of dimensions an array can have in C?


Multi

What C keyword is used to declare an array?


Array